# coding=utf-8
class Solution:
    def threeSumClosest(self, nums: list, target: int) -> int:
        nums.sort()
        n = len(nums)
        res = 10 ** 7
        catch = 1000
        for i in range(n - 2):
            if i > 0 and nums[i] == nums[i - 1]:
                continue
            l = i + 1
            r = n - 1
            while l < r:
                if l == r - 1:
                    break
                if nums[i] + nums[l] + nums[r] == target:
                    return target
                elif nums[i] + nums[l] + nums[r] < target:
                    catch = abs(nums[i] + nums[l] + nums[r] - target)
                    if catch < res:
                        res = catch
                        last = nums[i] + nums[l] + nums[r]
                    l += 1
                else:
                    catch = abs(nums[i] + nums[l] + nums[r] - target)
                    if catch < res:
                        res = catch
                        last = nums[i] + nums[l] + nums[r]
                    r -= 1
            catch = abs(nums[i] + nums[l] + nums[r] - target)
            if catch < res:
                res = catch
                last = nums[i] + nums[l] + nums[r]
        return last

a = Solution()
print(a.threeSumClosest([-3,-2,-5,3,-4],-1))
